package com.wpml.search.util;

import com.alibaba.fastjson.JSON;
import com.wpml.search.config.ElasticsearchConfig;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: wp
 * @date: 2019-09-02 10:43
 **/
public class EsClientUtil {

    private static RestHighLevelClient esClient;

    private static int dataSize = 500;

    public EsClientUtil(RestHighLevelClient esClient) {
        EsClientUtil.esClient = esClient;
    }

    /**
     * @description: 查询某个索引下的全部数据
     * @author: wang pei
     * @date: 2020/5/9 16:57
     **/
    public void queryAll(String index, SearchRequest searchRequest) {
        searchRequest.indices(index);
        // 构建查询条件
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        searchBuilder.size(dataSize);
    }

    public long count(String index, CountRequest countRequest) throws IOException {
        countRequest.indices(index);

        CountResponse response = esClient.count(countRequest, ElasticsearchConfig.COMMON_OPTIONS);
        return response.getCount();
    }

    /**
     * @description: 创建索引(示例)
     * @author: wang pei
     * @date: 2020/5/9 18:20
     **/
    public void createIndex(String indexName) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest(indexName);

        /*Map<String, Object> message = new HashMap<>();
        message.put("type", "text");
        Map<String, Object> properties = new HashMap<>();
        properties.put("message", message);
        Map<String, Object> mapping = new HashMap<>();
        mapping.put("properties", properties);
        request.mapping(mapping);*/

        esClient.indices().create(request, ElasticsearchConfig.COMMON_OPTIONS);
    }

    public void saveData() {

    }




    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = null;
        try {
            RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.33.30", 9200, "http"));

            client = new RestHighLevelClient(builder);

//        testSearch(client);

//            testCount(client);

            testCreateIndex("user_info", client);


            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    public static void testCreateIndex(String indexName, RestHighLevelClient client) throws IOException {

        /*CreateIndexRequest request = new CreateIndexRequest(indexName);

        client.indices().create(request, ElasticsearchConfig.COMMON_OPTIONS);*/

        IndexRequest indexRequest = new IndexRequest(indexName);

        indexRequest.id("1");
        UserEs user = new UserEs().setUserName("孙尚香").setAge(25).setGender("F");

        indexRequest.source(JSON.toJSONString(user), XContentType.JSON);


        IndexResponse index = client.index(indexRequest, ElasticsearchConfig.COMMON_OPTIONS);
        System.out.println(index.toString());
    }

    private static void testCount(RestHighLevelClient client) throws IOException {
        CountRequest request = new CountRequest();
        request.indices("user_info");
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();

        searchBuilder.query(QueryBuilders.matchAllQuery());

        request.source(searchBuilder);

        CountResponse count = client.count(request, ElasticsearchConfig.COMMON_OPTIONS);

        System.out.println("总记录数====：" + count.getCount());

        EsClientUtil esClientUtil = new EsClientUtil(client);

        System.out.println("总记录数：" + esClientUtil.count("user_info", request));



    }

    public static void testSearch(RestHighLevelClient esClient) throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("bank");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查询所有
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//        searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));
        // 聚合
        searchSourceBuilder.aggregation(AggregationBuilders.terms("ageAgg").field("age"));

        searchSourceBuilder.aggregation(AggregationBuilders.avg("balanceAvg").field("balance"));

        searchSourceBuilder.size(20);

        System.out.println(searchSourceBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = esClient.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

        System.out.println("记录数" + searchResponse.getHits().getTotalHits().value);

        System.out.println(searchResponse);

    }

}
